{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d13ebbb",
   "metadata": {},
   "outputs": [],
   "source": [
    "!python3 -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu\n",
    "!python3 -m pip install tokenizers -U\n",
    "!python3 -m pip install transformers -U"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a8a4bb6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
    "import jsonlines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff804403",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the tokenizer and model from Hugging Face\n",
    "\n",
    "model_id = \"meta-llama/Llama-2-7b-hf\"\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    model_id,\n",
    "    torch_dtype=torch.float32,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f218ba6",
   "metadata": {},
   "source": [
    "## looping over multiple prompts and logits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c567f8d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save to disk\n",
    "output_path = \"golden_data_llama2-7b.jsonl\"\n",
    "\n",
    "\n",
    "# Your prompt text\n",
    "prompt_texts = [\"I love to\", \"Today is a\", \"What is the\"]\n",
    "all_data_to_save = []\n",
    "\n",
    "\n",
    "for prompt_text in prompt_texts:\n",
    "  # Encode the prompt text\n",
    "  input_ids = tokenizer.encode(prompt_text, return_tensors=\"pt\")\n",
    "\n",
    "  # Get the logits for the prompt + completion\n",
    "  with torch.no_grad():\n",
    "    outputs = model(input_ids)\n",
    "    logits = outputs.logits\n",
    "\n",
    "    # Convert logits to fp32\n",
    "    logits = logits.cpu().numpy().astype(\"float32\")\n",
    "\n",
    "    # Prepare data to be saved\n",
    "    data_to_save = {\n",
    "        \"prompt\": prompt_text,\n",
    "        \"tokens\": input_ids.tolist()[0],\n",
    "        \"logits\": logits.tolist()[0],  # Convert numpy array to list for JSON serialization\n",
    "    }\n",
    "    all_data_to_save.append(data_to_save)\n",
    "\n",
    "with jsonlines.open(output_path, \"w\") as f:\n",
    "  f.write_all(all_data_to_save)\n",
    "\n",
    "\n",
    "print(f\"Data saved to {output_path}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
